package com.dcbeida.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.HomeActivity;
import com.dcbeida.activity.addnewpatient.historyofsmoking.TypeAct;
import com.dcbeida.activity.sales.StoresalesActivity;
import com.dcbeida.activity.salsesdedail.ReturnDetailActivity;
import com.dcbeida.activity.salsesdedail.SalsesDetailActivity;
import com.dcbeida.activity.zyff.ZyWithGaDetailActivity;
import com.dcbeida.adapter.SalsesAdapter;
import com.dcbeida.bean.Drug;
import com.dcbeida.bean.DrugListBean;
import com.dcbeida.bean.Patient;
import com.dcbeida.bean.PatientList;
import com.dcbeida.bean.Sales;
import com.dcbeida.bean.Tag;
import com.dcbeida.fragment.salsesFragment.SalsesContract;
import com.dcbeida.fragment.salsesFragment.SalsesPersenter;
import com.dcbeida.utils.Constants;
import com.dcbeida.utils.Utils;
import com.dcbeida.widget.DataLoadDirection;
import com.dcbeida.widget.FlowLayout;
import com.dcbeida.widget.XListView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.dcbeida.utils.Utils.showTip;


/**
 * 销售
 * Created by swt on 2016/11/17.
 */

public class SalsesFragment extends BaseFragment implements XListView.IXListViewListener, SalsesContract.View,
        AdapterView.OnItemClickListener, View.OnClickListener {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.tv_left)
    TextView tv_left;
    @Bind(R.id.rel_title1)
    RelativeLayout relTitle1;
    @Bind(R.id.myList)
    XListView myList;
    @Bind(R.id.ll_no_data)
    LinearLayout llNoData;
    private List<Object> datalist;
    private SalsesAdapter adapter;
    private SalsesPersenter mPresent;

    private boolean isEdit = false;
    private boolean isEnd = false;// 是否有更多
    private int Totle = 0;//
    private int pageindex = 0;
    private int pagesize = 10;

    int type = DataLoadDirection.Refresh;


    @Override
    public View initViews() {
        View view = View.inflate(mActivity, R.layout.salses_fragment, null);
        ButterKnife.bind(this, view);
        tv_left.setText(getString(R.string.add));
        tv_left.setVisibility(View.VISIBLE);
        return view;
    }


    EditText et_tel_or_name;
    EditText et_orderNo;
    LinearLayout lin_date_start;
    LinearLayout lin_date_end;
    TextView tv_start;
    TextView tv_end;
    FlowLayout fl_yp;
    FlowLayout fl_order_type;
    TextView tv_reset;
    TextView tv_confim;

    private static Handler mainHandler;
    private static final int MSG_SEARCH = 1;

    private MyTextWatcher textWatcher = new MyTextWatcher();


    private class MyTextWatcher implements TextWatcher {
        int type;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            if (et_tel_or_name.getText().toString().trim().length() < 2) {
                return;
            }
            Pattern p = Pattern.compile("[0-9]*");
            Matcher m = p.matcher(s);
            if (m.matches()) {
                //输入的是手机号码
                if (et_tel_or_name.getText().length() == 11) {
                    type = 1;
                } else {
                    return;
                }

            } else {
                type = 3;
            }

            //否则延迟800ms开始搜索
            if (mainHandler.hasMessages(MSG_SEARCH)) {
                mainHandler.removeMessages(MSG_SEARCH);
            }
            Message message = Message.obtain(mainHandler, new Runnable() {
                @Override
                public void run() {
                    mPresent.getPatientInfo(type, s.toString());
                }
            });
            message.what = MSG_SEARCH;
            mainHandler.sendMessageDelayed(message, 2000);

        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainHandler = new Handler(Looper.getMainLooper());
        View leftView = ((HomeActivity) mActivity).getLeftView();
        et_tel_or_name = (EditText) leftView.findViewById(R.id.et_tel_or_name);
        et_orderNo = (EditText) leftView.findViewById(R.id.et_orderNo);
        lin_date_start = (LinearLayout) leftView.findViewById(R.id.lin_date_start);
        lin_date_end = (LinearLayout) leftView.findViewById(R.id.lin_date_end);
        tv_start = (TextView) leftView.findViewById(R.id.tv_start);
        tv_end = (TextView) leftView.findViewById(R.id.tv_end);
        fl_yp = (FlowLayout) leftView.findViewById(R.id.fl_yp);
        fl_order_type = (FlowLayout) leftView.findViewById(R.id.fl_order_type);
        tv_reset = (TextView) leftView.findViewById(R.id.tv_reset);
        tv_confim = (TextView) leftView.findViewById(R.id.tv_confim);

        lin_date_start.setOnClickListener(this);
        lin_date_end.setOnClickListener(this);
        tv_reset.setOnClickListener(this);
        tv_confim.setOnClickListener(this);
        fl_yp.setSpec(Utils.dip2px(mActivity, 10), Utils.dip2px(mActivity, 8));
        fl_order_type.setSpec(Utils.dip2px(mActivity, 10), Utils.dip2px(mActivity, 8));
        //data//

        addDrugTas(fl_yp);
        addOrderStatusTas(fl_order_type);

        et_tel_or_name.addTextChangedListener(textWatcher);
    }

    @Override
    public void initData() {
        tvTitle.setText(R.string.xsjl);
        tvRight.setText(R.string.fliter);

        datalist = new ArrayList<Object>();
        myList.setPullLoadEnable(false);
        myList.setPullRefreshEnable(true);
        myList.setXListViewListener(this);
        myList.setVerticalScrollBarEnabled(false);// 去掉竖向滚动条
        myList.setOnItemClickListener(this);
        adapter = new SalsesAdapter(getActivity());
        myList.setAdapter(adapter);

        mPresent = new SalsesPersenter(this, getActivity());
        mPresent.getList("", pageindex, pagesize);
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {   // 不在最前端显示 相当于调用了onPause();
        } else {  // 在最前端显示 相当于调用了onResume();
            //刷新数据
        }
    }


    @Override
    public void setPresenter(SalsesContract.Persent presenter) {

    }

    @Override
    public void showTelTip(String msg) {
        showTip(getActivity(), msg);
    }

    @Override
    public void showView(boolean hasData) {

    }

    @Override
    public void showList(ArrayList<Sales.ListBean> list) {

        if (list.size() < 10)
            isEnd = false;
        else
            isEnd = true;

        Totle = adapter.getmArrayList().size() + list.size();


        if (type == DataLoadDirection.Refresh) {
            myList.stopRefresh();
            pageindex = 0;
            adapter.clearList();
        } else if (type == DataLoadDirection.LoadMore) {
            myList.stopLoadMore();
            pageindex++;
        }

        if (isEnd) {
            myList.showFooterView();
            myList.setPullLoadEnable(true);
        } else {
            myList.hideFooterView();
            myList.setPullLoadEnable(false);
        }

        adapter.setmArrayList(list);

        if (adapter.getCount() > 0) {
            myList.setVisibility(View.VISIBLE);
            llNoData.setVisibility(View.GONE);
        } else {
            myList.setVisibility(View.GONE);
            llNoData.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showPatientList(final PatientList list) {

        if (list.getList() == null || list.getList().size() == 0)
            return;

        if (list.getList().size() == 1) {

            mPresent.setPatientid(list.getList().get(0).getId());
        } else {
            final ListPopupWindow listPopupWindow;
            listPopupWindow = new ListPopupWindow(mActivity);
            listPopupWindow.setAdapter(new ArrayAdapter<Patient>(mActivity, android.R.layout.simple_list_item_1, list.getList()));//用android内置布局，或设计自己的样式
            listPopupWindow.setAnchorView(et_tel_or_name);//以哪个控件为基准，在该处以logId为基准
            listPopupWindow.setModal(true);
            listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Patient patient = list.getList().get(position);
                    et_tel_or_name.removeTextChangedListener(textWatcher);
                    et_tel_or_name.setText(patient.getTruename());
                    et_tel_or_name.addTextChangedListener(textWatcher);
                    mPresent.setPatientid(patient.getId());
                    listPopupWindow.dismiss();
                }
            });
            listPopupWindow.show();

        }

    }

    @Override
    public void onRefresh() {
        // 执行刷新任务
        type = DataLoadDirection.Refresh;
        mPresent.getList("", 0, pagesize);
    }

    public void reFresh() {
        onRefresh();
    }

    @Override
    public void onLoadMore() {
        // 执行加载更多任务
        type = DataLoadDirection.LoadMore;
        if (isEnd) {
            mPresent.getList("", pageindex + 1, pagesize);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        Sales.ListBean bean = (Sales.ListBean) adapter.getItem(position - 1);

        if (bean.getType() == 0) {
            bundle.putSerializable("Sales.ListBean", bean);
            intent.putExtras(bundle);
            if (bean.getRefundid().equals("0")) {
                //正常销售详情
                ((HomeActivity) getActivity()).showActivity(SalsesDetailActivity.class, bundle);
            } else {
                //退货详情
                ((HomeActivity) getActivity()).showActivityForResult(ReturnDetailActivity.class, bundle, Constants.ONE);
            }
        } else {
            bundle.putString("orderId", bean.getId());
            bundle.putString("parentid", bean.getPatientid());
            bundle.putSerializable("Sales.ListBean", bean);
            ((HomeActivity) getActivity()).showActivity(ZyWithGaDetailActivity.class, bundle);
        }
    }


    @OnClick({R.id.tv_right, R.id.ll_no_data, R.id.tv_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                ((HomeActivity) mActivity).showActivity(StoresalesActivity.class, null);
                break;
            case R.id.tv_right:

                ((HomeActivity) mActivity).startAnim();
                break;
            case R.id.ll_no_data:
                mPresent.getList("", 0, pagesize);
                break;
            case R.id.lin_date_start://开始时间
                selectDate(true);
                break;
            case R.id.lin_date_end://结束时间
                selectDate(false);
                break;
            case R.id.tv_reset://
                et_tel_or_name.setText("");


                et_orderNo.setText("");
                tv_start.setText("");
                tv_end.setText("");
                resetDrugTas(fl_yp);
                resetStatusTas(fl_order_type);

                mPresent.setBegindate("");
                mPresent.setEnddate("");
                mPresent.setPatientid(0);
                mPresent.setOrderid("");
                mPresent.setOrderstatus(0);
                mPresent.setDrugid("");
                break;
            case R.id.tv_confim:
                if (!TextUtils.isEmpty(et_orderNo.getText())) {
                    mPresent.setOrderid(et_orderNo.getText().toString().trim());
                }
//                if (fl_yp.getTag() != null) {
//                    int pos = (int) fl_yp.getTag();
//                    DrugListBean drugListBean = MyApplication.getInstance().getmDrugBean();
//                    if (drugListBean != null) {
//                        mPresent.setDrugid(drugListBean.getList().get(pos).getDrugid());
//                    }
//                }

                DrugListBean drugListBean = MyApplication.getInstance().getmDrugBean();
                int childCount = fl_yp.getChildCount();
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < childCount; i++) {
                    View itemView = fl_yp.getChildAt(i);
                    if ((boolean) itemView.getTag()) {
                        stringBuilder.append(drugListBean.getList().get(i).getDrugid()).append(",");
                    }
                }

                if (stringBuilder.length() > 1) {
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                }
                mPresent.setDrugid(stringBuilder.toString());


                View v1 = fl_order_type.getChildAt(0);
                View v2 = fl_order_type.getChildAt(1);
                View v3 = fl_order_type.getChildAt(2);
                View v4 = fl_order_type.getChildAt(3);
                boolean b1 = (boolean) v1.getTag();
                boolean b2 = (boolean) v2.getTag();
                boolean b3 = (boolean) v3.getTag();
                boolean b4 = (boolean) v4.getTag();

                if (b1 && b2) {
                    mPresent.setOrderstatus(3);
                } else if (b1) {
                    mPresent.setOrderstatus(1);
                } else if (b2) {
                    mPresent.setOrderstatus(2);
                } else if (b3) {
                    mPresent.setOrderstatus(10);
                } else if (b4) {
                    mPresent.setOrderstatus(20);
                } else {
                    mPresent.setOrderstatus(0);

                }
                ((HomeActivity) mActivity).goBackAnim(new Runnable() {
                    @Override
                    public void run() {
                        onRefresh();
                    }
                });
                break;
        }
    }

    private void selectDate(final boolean isStartDate) {
        Calendar d = Calendar.getInstance(Locale.CHINA);
        Date myDate = new Date();
        d.setTime(myDate);
        int year = d.get(Calendar.YEAR);
        int month = d.get(Calendar.MONTH);
        int day = d.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(mActivity,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        Log.i("fancl", "year:" + year + "//monthOfYear:" + monthOfYear + "//dayOfMonth:" + dayOfMonth);
                        Calendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
                        String pattern = "yyyy-MM-dd";
                        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
                        String date = dateFormat.format(cal.getTime());
                        if (isStartDate) {
                            mPresent.setBegindate(date);
                            tv_start.setText(date);
                        } else {
                            mPresent.setEnddate(date);
                            tv_end.setText(date);
                        }


                    }
                }, year, month, day);

        datePickerDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.ONE && resultCode == getActivity().RESULT_OK) {
            onRefresh();
        }
    }


    private class TagsOnclickListener implements View.OnClickListener {
        int mPos;
        FlowLayout mF;

        TagsOnclickListener(int pos, FlowLayout flowLayout) {
            this.mPos = pos;
            this.mF = flowLayout;

        }

        @Override
        public void onClick(View v) {
            ((TextView) v.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_ffffff_Size12);
            v.setBackgroundResource(R.drawable.shape_rectangle_c_0c87ea);
            if (mF.getTag() != null) {
                int prePosition = (int) mF.getTag();
                View preView = mF.getChildAt(prePosition);
                ((TextView) preView.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
                preView.setBackgroundResource(R.drawable.shape_fliter_rect);
            }
            mF.setTag(mPos);
        }
    }


    private class TorderOnclickListener implements View.OnClickListener {


        @Override
        public void onClick(View v) {
            boolean isSelect = (boolean) v.getTag();
            if (isSelect) {
                ((TextView) v.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
                v.setBackgroundResource(R.drawable.shape_fliter_rect);
                v.setTag(false);
            } else {
                ((TextView) v.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_ffffff_Size12);
                v.setBackgroundResource(R.drawable.shape_rectangle_c_0c87ea);
                v.setTag(true);
            }

        }
    }


    private class TorderOnclickListener2 implements View.OnClickListener {


        FlowLayout mParent;

        TorderOnclickListener2(FlowLayout parent) {
            mParent = parent;
        }

        @Override
        public void onClick(View v) {
            boolean isSelect = (boolean) v.getTag();
            if (isSelect) {
                ((TextView) v.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
                v.setBackgroundResource(R.drawable.shape_fliter_rect);
                v.setTag(false);
            } else {
                ((TextView) v.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_ffffff_Size12);
                v.setBackgroundResource(R.drawable.shape_rectangle_c_0c87ea);
                v.setTag(true);
            }


            if (v == mParent.getChildAt(2)) {
                if (((boolean) v.getTag()) == true) {
                    View v0 = mParent.getChildAt(0);
                    ((TextView) v0.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
                    v0.setBackgroundResource(R.drawable.shape_fliter_rect);
                    v0.setTag(false);
                    View v1 = mParent.getChildAt(1);
                    ((TextView) v1.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
                    v1.setBackgroundResource(R.drawable.shape_fliter_rect);
                    v1.setTag(false);
                }
            } else {
                if (((boolean) v.getTag()) == true) {
                    if (v == mParent.getChildAt(3))
                        return;
                    View v2 = mParent.getChildAt(2);
                    ((TextView) v2.findViewById(R.id.tvTagName)).setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
                    v2.setBackgroundResource(R.drawable.shape_fliter_rect);
                    v2.setTag(false);
                }
            }


        }
    }


    // 筛选药品id的布局
    private void addDrugTas(final FlowLayout flowLayout) {
        DrugListBean drugListBean;
        if ((drugListBean = MyApplication.getInstance().getmDrugBean()) == null)
            return;
        if (drugListBean.getList() == null) return;
//        //todo 要删除的
//        Drug drug1 = new Drug();
//        drug1.setDrugid(4);
//        drug1.setDrugname("盐酸替33尼片");
//        drug1.setShopid(362);
//        drugListBean.getList().add(drug1);
        for (int i = 0; i < drugListBean.getList().size(); i++) {
            Drug drug = drugListBean.getList().get(i);
            final View view = LayoutInflater.from(mActivity).inflate(R.layout.drug_tag_item, null);
            final TextView tvTagName = (TextView) view.findViewById(R.id.tvTagName);
            tvTagName.setText(drug.getDrugname());
            tvTagName.setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
            view.setBackgroundResource(R.drawable.shape_fliter_rect);
            //view.setOnClickListener(new TagsOnclickListener(i, flowLayout));

            view.setTag(false);
            view.setOnClickListener(new TorderOnclickListener());
            flowLayout.addView(view);
        }


    }

    private void resetDrugTas(final FlowLayout flowLayout) {
        if (flowLayout.getTag() != null) {
            int position = (int) flowLayout.getTag();
            View view = flowLayout.getChildAt(position);
            if (view == null)
                return;
            final TextView tvTagName = (TextView) view.findViewById(R.id.tvTagName);
            tvTagName.setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
            view.setBackgroundResource(R.drawable.shape_fliter_rect);

        }

    }

    private void addOrderStatusTas(final FlowLayout flowLayout) {
        final View view = LayoutInflater.from(mActivity).inflate(R.layout.drug_tag_item, null);
        final TextView tvTagName = (TextView) view.findViewById(R.id.tvTagName);
        tvTagName.setText("退货订单");
        tvTagName.setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
        view.setBackgroundResource(R.drawable.shape_fliter_rect);
        view.setTag(false);
        view.setOnClickListener(new TorderOnclickListener2(flowLayout));
        flowLayout.addView(view);
        final View view1 = LayoutInflater.from(mActivity).inflate(R.layout.drug_tag_item, null);
        final TextView tvTagName1 = (TextView) view1.findViewById(R.id.tvTagName);
        tvTagName1.setText("信息缺失订单");
        tvTagName1.setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
        view1.setBackgroundResource(R.drawable.shape_fliter_rect);
        view1.setTag(false);
        view1.setOnClickListener(new TorderOnclickListener2(flowLayout));
        flowLayout.addView(view1);

        final View view2 = LayoutInflater.from(mActivity).inflate(R.layout.drug_tag_item, null);
        final TextView tvTagName2 = (TextView) view2.findViewById(R.id.tvTagName);
        tvTagName2.setText("正常订单");
        tvTagName2.setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
        view2.setBackgroundResource(R.drawable.shape_fliter_rect);
        view2.setTag(false);
        view2.setOnClickListener(new TorderOnclickListener2(flowLayout));
        flowLayout.addView(view2);

        final View view3 = LayoutInflater.from(mActivity).inflate(R.layout.drug_tag_item, null);
        final TextView tvTagName3 = (TextView) view3.findViewById(R.id.tvTagName);
        tvTagName3.setText("赠送订单");
        tvTagName3.setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
        view3.setBackgroundResource(R.drawable.shape_fliter_rect);
        view3.setTag(false);
        view3.setOnClickListener(new TorderOnclickListener2(flowLayout));
        flowLayout.addView(view3);

    }

    private void resetStatusTas(final FlowLayout flowLayout) {
        for (int i = 0; i < flowLayout.getChildCount(); i++) {
            View view = flowLayout.getChildAt(i);
            view.setTag(false);
            final TextView tvTagName = (TextView) view.findViewById(R.id.tvTagName);
            tvTagName.setTextAppearance(mActivity, R.style.TextAppear_Theme_c_444444_Size12);
            view.setBackgroundResource(R.drawable.shape_fliter_rect);
        }
    }
}
